<?php
/** 课程--爱课堂
 * Created by PhpStorm.
 * User: denh
 * Date: 16/5/30
 * Time: 下午1:33
 */
//爱课程
require_once ROOT_PATH . 'bs/bs.QunLiaotian.php';

class CourseController extends BaseController {

    public $data;

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);

        $this->redirectToWeixinForOpenid();
    }

    //爱课堂列表
    function index() {

        $sign_id = $this->request('sign_id', -1);

        //标签列表
        $doSign = new DoCourse_sign();
        $signList = $doSign->orderby('id asc')->rows();
        foreach ($signList as $k=>$v) {
            if($v['id'] == $sign_id) {
                $current_sign = $v['name'];
            }
        }
        if (!isset($current_sign)) {
            $current_sign = '全部课程';
        }

        $do_course = new Do语音课程();
        $do_user = new Do用户();
        $do_test_user = new DoTest_user();

        $where = "a.type = '视频' and a.状态!='开始'";
        $where1 = "a.type = '视频' and a.状态='开始'"; //正在上课

        if ($sign_id > 0) {
            $where .= " and a.sign_id = '$sign_id'";
        }
        //判断用户是否是测试人员
        $do_test_user->set_openId($this->openId());

        if ($do_test_user->where($do_test_user->data)->count()) {
            $count = $do_course->fields('count(a.id)')->where($where)->getOneField();
        } else {
            $where.=" and 发送='已发送' and is_test=0";
            $where1.=" and 发送='已发送' and is_test=0";
            $count = $do_course->fields('count(a.id)')->where($where)->getOneField();
        }

        //正在直播在课程
        $live_course = $do_course->leftJoin($do_user, 'b','a.讲课专家id = b.id')
            ->leftJoin($doSign, 's', 'a.sign_id = s.id')
            ->fields('a.*,b.`name`,b.`头像`,b.seller_name, s.name sign_name')
            ->orderby('添加时间 desc')
            ->where($where1)->rows();

        $do_course = new Do语音课程();
        $page = new \tools\Page($count, 10);
        //非直播课程
        $course_list = $do_course->leftJoin($do_user, 'b','a.讲课专家id = b.id')
            ->leftJoin($doSign, 's', 'a.sign_id = s.id')
            ->fields('a.*,b.`name`,b.`头像`,b.seller_name, s.name sign_name')
            ->where($where)
            ->orderby('添加时间 desc')
            ->offset($page->limit)
            ->limit($page->pagesize)->rows();

        $course_detail_url = $this->url('course', 'course_detail');
        $course_history_url = $this->url('course','course_history');

        require $this->template;
    }

    //课堂详情
    function course_detail() {
        $课程id = (isset($_GET['id'])) ? $_GET['id'] : "0";
        $do_course = new Do语音课程();
        $do_course_reg = new Do语音课程报名();
        $do_user = new Do用户();
        $do_course->leftJoin($do_user,'b','a.`讲课专家id`= b.id');

        //医师认证
        $renzheng_url = $this->url('user','user_base');
        $yuyin_url = $this->url('course', 'course_detail', array("id" => $课程id));

        //语音课程详情
        $course_detail = $do_course->fields(' a.*,b.name,b.description,b.`头像`')->where(array('a.id'=>$课程id))->row();

        //用户是否同一时间报了多堂课程
        //$re_course_reg = $this->repeat_course_reg($course_detail->data, $课程id);
        $do_course_reg->set_课程id($课程id);
        $do_course_reg->set_状态('报名');

        //已经报名人数
        $course_reg_count = $do_course_reg->fields("COUNT('id')")->where($do_course_reg->data)->getOneField();

        //get当前用户是否报名该课程
        $where_is_reg = array('用户id' => $_SESSION['vo用户数据']['id'], '课程id' => $课程id);
        $user_is_reg = $do_course_reg->fields('id,状态')->where($where_is_reg)->row();


        if ($do_course->get_chatId()) {
            #网易云信聊天
            $course_shi_url = $this->url('course','video_chat', array('id'=>$课程id, 't'=> time()));
        } else {
            $param = array('tid' => $课程id);
            $course_shi_url = $this->url('group','webSocket_video',$param);
        }

        if (!$user_is_reg->data) $user_is_reg->data = array('id' => 0, '状态' => '取消报名');
        if ($user_is_reg->data['状态'] === '报名') $状态 = '取消报名';
        else $状态 = '报名';


        #更新浏览数
        article_statistic(2, $_SESSION['vo用户数据']['id'], $_GET['id']);

        //按钮状态判断
        //4-15之前视频播放的链接存放不一样
        if ($course_detail->data['结束时间'] < '2016-04-15 00:00:00')
        {
            $课程 = $course_detail->data['视频url'];
        } else {
           // $课程 = $course_shi_url . '&视频链接=' . $course_detail->data['视频url'] . '&群id=' . $course_detail->data['群id'];
            $课程 = $course_shi_url . '&video_url=' . $course_detail->data['视频url'] . '&groupId=' . $course_detail->data['群id'];
        }

        //直接进入课程url-  专家，已开始课程并报名，已结束课程
        $enter_course_url = "window.location='".$课程."'";
        //报名——报名已满  预备状态课程，已开始课程位报名
        $reg_max_url = "f人数()";

         //对应专家直接进入课程
        if ($_SESSION['vo用户数据']['id'] == $course_detail->data['讲课专家id']) {
            $onclick = $enter_course_url;
            $botton = "进入课程";
            $background = "#5E94C6";
        } else {
            if ($user_is_reg->data && $course_detail->data['状态'] === '预备') {
                if ($状态 === '报名') {
                    if (($course_detail->data['课堂人数上限'] != null) && ($course_reg_count > $course_detail->data['课堂人数上限'])) {

                        $onclick = $reg_max_url;
                        $botton = "报名已满";
                        $background = "red";
                    } else {
                        $onclick = "f报名('" . $状态 . "','" . $user_is_reg->data['id'] . "')";
                        $botton = "报名上课" ;
                        $background = "#20BE35";
                    }
                } else {
                    $onclick = "f报名('" . $状态 . "'," . $user_is_reg->data['id'] . ")";
                    $botton = "取消报名";
                    $background = "#B5B5B5";

                }
            } else if ($course_detail->data['状态'] === '开始') {
                if ($user_is_reg->data['状态'] == '报名') {
                    $onclick = $enter_course_url;
                    $botton = "进入课程";
                    $background = "#5E94C6";
                } else {
                    if (($course_detail->data['课堂人数上限'] != null) && ($course_reg_count > $course_detail->data['课堂人数上限'])) {
                        $onclick = $reg_max_url;
                        $botton = "报名已满";
                        $background = "red";
                    }else{
                        $onclick = "f报名('" . $状态 . "','" . $user_is_reg->data['id'] . "')";
                        $botton = "报名上课";
                        $background = "#20BE35";
                    }
                }
            } else if ($user_is_reg->data && $course_detail->data['状态'] === '结束') {
                $onclick = $enter_course_url;
                $botton = "课程回顾";
                $background = "#5E94C6";

            }
        }
        //按钮状态判断结束

        //分享相关
        $desc = mb_substr(strip_tags($course_detail->data['详情']), 0, 100, 'utf-8');
        $desc = str_replace('&nbsp', ' ', $desc);
        $avatar = trim($course_detail->data['头像']);
        if (!$avatar) {
            $avatar = G_SITE_CDN .'/business/img/default_avatar.jpg';
        }
        if (substr($avatar, 0, 4) != 'http') {
            $avatar = G_SITE_CDN .'/business/'. $avatar;
        }
        $ajax_update_isreg_url = $this->url('course', 'update_isreg');

        $doUser = new Do用户();
        $doUser->set_openID($_SESSION['vo用户数据']['openID']);

        $re = $doUser->where($doUser->data)->row();
        #确认用户是否真的取关
        if ($doUser->get_unsubscribe() == 1 and $this->isSubscribe()) {
            $doUser->set_unsubscribe(0);
            $doUser->set_unsubscribe_time('');
            $doUser->save();
        }

        if (!$re or $doUser->get_unsubscribe() == 1) {
            $user_status = 1; #未关注

        } elseif ($doUser->get_认证() == 1) {
            $user_status = 2; #已关注 未认证
        } else {
            $user_status = 3; #已关注 已认证
        }


        if(isset($_GET['from'])|| empty($_SERVER['HTTP_REFERER'])){
            $course_index_url = $this->url('course','index');
        }else{
            $course_index_url="javascript:history.go(-1);";
        }

        require $this->template;

    }

    //课堂云信聊天
    function video_chat() {
        $id = $this->request('id', '', true);
        $do = new Do语音课程();
        if (!$do->row($id)) {
            $this->errorPage('参数id错误');
        }

        $doUser = new Do用户();
        $doUser->set_openID($this->openId());
        if (!$doUser->where($doUser->data)->row()) {
            $this->errorPage('请先关注爱贝儿医公众号');
        }

        $doUserDoctor = new Do医师详情();
        $doUserDoctor->set_用户id($doUser->get_id());
        $doUserDoctor->where($doUserDoctor->data)->row();

        $doTeacher = new Do用户();
        $doTeacher->set_id($do->get_讲课专家id());
        $doTeacher->fields("id, name, userCenterID")->where($doTeacher->data)->row();

        $group_id = $do->get_群id();

        $群聊天 = new C群聊天('');
        $c用户 = new C用户(C信息中心::get实列根据公众号OpenId());

        $用户是否是群用户 = $c用户->fc查看用户是否是群用户($group_id);
        if(!$用户是否是群用户){
            $加入视频群聊 = $c用户->fj加入视频群聊($group_id);
        }
        $群聊天->f进入课程($doUser->get_id(), $group_id);


        $this->data = $do->data;
        $this->data['doUser'] = $doUser;
        $this->data['doUserDoctor'] = $doUserDoctor;
        $this->data['doTeacher'] = $doTeacher;
        require $this->template;
    }

    //写入聊天记录
    function write_chat_record() {
        $groupId = $this->request('groupId', '', true);
        $type    = $this->request('type', '', true);
        $message    = $this->request('message', '', true); #聊天文本或者图片，声音文件路径

        $openId = $this->openId();
        $doUser = new Do用户();
        $user_id = $doUser->fields('id')->where("openId = '$openId'")->getOneField();
        $Chat = new C群聊天('');
        $re = $Chat->f写入聊天记录($groupId, $user_id, $type, $message);
        if (!$re) {
            logger()->logInfo("聊天记录保存失败 :". var_export($_REQUEST, true));
            $this->jsonOutPut(-1, '聊天记录保存失败');
        }
        $this->jsonOutPut(0, 'ok');
    }

    //课程回顾--咨询
    function course_history() {

        $do_zixun_detail = new Do咨询详情();
        $do_zixun = new Do咨询信息();

        $where = "a.news_type = 2 and b.发送 = '已发送'";
        $course_h_list = $do_zixun_detail
            ->fields("a.id, a.文章url, a.标题, a.图片url, date_format(a.添加时间,'%Y-%m-%d') as 添加时间")
            ->leftJoin($do_zixun, 'b', "a.咨询id = b.id")
            ->where($where)
            ->orderby('a.id desc ')
            ->offset(0)->limit(10)->rows();
        $ajax_course_url = $this->url('course', 'history_course_ajax');

        logger()->logInfo($do_zixun_detail->sql);

        if(isset($_GET['from'])){
            $course_index_url = $this->url('course','index');
        }else{
            $course_index_url="javascript:history.go(-1);";
        }
        require $this->template;
    }

    //ajax 处理分页加载
    function history_course_ajax() {
        $do_zixun_detail = new Do咨询详情();
        $do_zixun = new Do咨询信息();

        $pageNum = intval($_REQUEST['page']);
        if ($pageNum <= 0) {
            $pageNum = 1;
        }
        $start = ($pageNum - 1) * 10;
        $where = "a.news_type = 2 and b.发送 = '已发送'";
        $res = $do_zixun_detail
            ->fields("a.id, a.文章url, a.标题, a.图片url, date_format(a.添加时间,'%Y-%m-%d') as 添加时间")
            ->leftJoin($do_zixun, 'b', "a.咨询id = b.id")
            ->where($where)
            ->orderby('a.id desc ')
            ->offset($start)->limit(10)->rows();

        if (count($res) <= 0) {
            echo "zero";
            //  break;
        }
        $str = "";
        foreach ($res as $k => $v) {
            $str .= "<div class='LoveRead_time'><div>{$v['添加时间']}</div></div><dl>";
            $str .= "<a href='" . $v['文章url'] . "'><dt><div class='img' style='background:url(" . $v['图片url'] . ") no-repeat center;background-size:cover;'><div><h1>" . $v['标题'] . "</h1></div></div></dt></a>";
            $str .= "</dl>";
        }
        echo $str;

    }

    //修改报名语音课程--报名/取消报名
    function update_isreg() {
        $状态 = $_REQUEST['状态'];
        $课程id = $_REQUEST['课程id'];
        $关注id = $_REQUEST['报名id'];
        $用户id = $_SESSION['vo用户数据']['id'];
        $课程人数限制 = $_REQUEST['课程人数限制'];

        if (!$状态 or !$课程id or !$用户id) {
            logger()->logInfo(sprintf("fg修改报名语音课程失败: 状态:%s  课程id:%s  关注id:%s  用户id:%s  课程人数限制:%s", $状态, $课程id, $关注id, $用户id, $课程人数限制));
            $this->jsonOutPut('-1','报名失败');
           // echo 0;
        }
        $do = new Do语音课程报名();
        //课堂报名是否已满
        if ($状态 == '报名' && $this->course_reg_maxnum($课程id, $课程人数限制)) {
            $this->jsonOutPut('2','报名人数已满');
           // echo '2';//报名人数已满
        }

        $do->set_课程id($课程id);
        $do->set_用户id($用户id);
        $do->where($do->data)->row();

        $do->set_状态($状态);
        $do->set_时间(date("Y-m-d H:i:s"));
        $关注 = $do->save();
        $this->jsonOutPut('1',$关注);
        //echo $关注;
    }

    //课程报名是否已满
    function course_reg_maxnum($course_id,$max_count) {
        $do_course_reg = new Do语音课程报名();
        $do_course_reg->set_课程id($course_id);
        $do_course_reg->set_状态('报名');
        $course_reg_count = $do_course_reg->fields("COUNT('id')")->where($do_course_reg->data)->getOneField();
        Logger::getInstance()->logInfo($do_course_reg->sql);
        Logger::getInstance()->logInfo("course_reg_maxnum___课程报名是否已满");
        Logger::getInstance()->logInfo($max_count);
        if ($course_reg_count > $max_count) {
            return true;
        }
        return false;
    }

    //用户重复报名
    function  repeat_course_reg($course_detail,$course_id) {
        $start_time = date("Y-m-d H:i:s", (strtotime($course_detail['开始时间']) - 1));
        $end_time = date("Y-m-d H:i:s", (strtotime($course_detail['结束时间']) + 1));

        //报名的时间不冲突的,未结束的,不是本课程的,而且未取消报名
        $sql = "SELECT count(a.`id`) as `num`  FROM `语音课程报名` a LEFT JOIN `语音课程` b  ON a.`课程id`=b.id WHERE a.`用户id` ='" . $_SESSION['vo用户数据']['id'] . "'   AND   b.`状态` !='结束'  AND b.id != '" . $course_id . "'
 AND a.`状态`='报名' AND
 ( b.`开始时间` between  '" . $start_time . "' AND '" . $end_time . "'
 OR
   b.`结束时间` between   '" . $start_time . "' AND '" . $end_time . "');";
        $do_course_reg=new Do语音课程报名();

        $时间冲突 = pdo()->selectAll($sql);
        return $时间冲突[0]['num'];
    }
}